package org.spider.core.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.model.Notice;
import org.spider.api.domain.model.SpiderFlow;
import org.spider.api.enums.NoticeType;
import org.spider.core.mapper.NoticeMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.util.List;

import static org.spider.core.utils.EmailUtil.sendMails;

@Service
public class NoticeService extends ServiceImpl<NoticeMapper, Notice>
        implements IService<Notice> {
    @Value("${email.subject}")
    private String subject;
    @Value("${email.content.start}")
    private String contentStart;
    @Value("${email.content.exception}")
    private String contentException;
    @Value("${email.content.end}")
    private String contentEnd;
    @Value("${email.from}")
    private String email_from;
    @Value("${email.token}")
    private String email_token;
    private static Logger log = LoggerFactory.getLogger(NoticeService.class);

    public void sendNotice(SpiderFlow flow, NoticeType type) {
        Notice notice = getById(flow.getId());
        log.info(type + " ,notice:" + notice);
        if (notice != null && StringUtils.isNotEmpty(notice.getEmail())) {
            String content = "";
            String sendSubject = subject;
            switch (type) {
                case start:
                    if (notice.checkStart()) {
                        content = contentStart;
                        subject += " - 流程开始执行";
                    }
                    break;
                case exception:
                    if (notice.checkException()) {
                        content = contentException;
                        subject += " - 流程发生异常";
                    }
                    break;
                case end:
                    if (notice.checkEnd()) {
                        content = contentEnd;
                        subject += "- 流程执行结束";
                    }
                    break;
            }
            //什么都没有，直接退出
            if (StringUtils.isEmpty(content)) return;
            content = "爬虫:[ "+ flow.getName() + " ],id=[ " + flow.getId() + " ] " + content;
            String[] recipients = notice.getEmail().split(";");
            try {
                sendMails(email_from,
                        List.of(recipients),
                        email_token,
                        sendSubject,
                        content);
            } catch (MessagingException e) {
                System.out.println("email error邮箱发送失败");
            }
        }

    }
}
